<template>
  <view class="w-full">
    <!-- 横向Tab -->
    <tab :list="tabList1" v-model:active="tab1" class="bg-[#e6f0ff] py-2 pb-0 mb-1 shadow box-border w-full"
      direction="horizontal" label="title">
      <template #tab="{ tab, idx, active }">
        <view class="flex-center border-b-4 border-b-solid px-6 py-2 rounded-t-xl"
          :class="active ? 'border-[#165DFF] bg-white shadow text-[#165DFF] font-bold' : 'border-transparent text-gray-500'">
          <text class="text-[28rpx] whitespace-nowrap">{{ tab.name }}</text>
        </view>
      </template>
    </tab>

    <view class="flex bg-white shadow-md overflow-hidden w-full">
    <!-- 纵向Tab -->
    <tab class="w-[200rpx] h-[60vh] bg-[#f5f5f5] mr-1 shadow" :list="tabList2" v-model:active="tab2"
      direction="vertical" label="name">
      <template #tab="{ tab, idx, active }">
        <view class="flex items-center border-l-4 border-l-solid px-4 py-2 whitespace-nowrap"
          :class="active ? 'border-green-500 bg-white text-green-500 font-bold' : 'border-transparent text-gray-500'">
          <text class="text-[28rpx] truncate w-full">{{ tab.name }}</text>
        </view>
      </template>
    </tab>

    <!-- 内容区 -->
    <view class="flex-1 h-[60vh]  overflow-hidden overflow-y-auto bg-white box-border">
      <tab :list="tabList3" v-model:active="tab3" class="bg-[#f6f6f6] shadow box-border w-full" direction="horizontal"
        label="name">
        <template #tab="{ tab, idx, active }">
          <view class="flex-center border-b-4 border-b-solid px-6 py-2"
            :class="active ? 'border-b-red-500 shadow text-red-500 font-bold' : 'border-b-transparent text-gray-500'">
            <text class="text-[28rpx] whitespace-nowrap">{{ tab.name }}</text>
          </view>
        </template>
      </tab>

      <view class="p-4 flex flex-wrap gap-x-4 gap-y-2">
        <nut-button @click="onAddTag(item)" type="success" class="rounded-xl px-6 py-2 shadow-sm" v-for="item in tabList4" :key="item.id">
          {{ item.name }}
        </nut-button>
      </view>

    </view>
    </view>
  </view>
</template>

<script setup>
import { ref, watch, onMounted } from "vue";
import tab from "./tab.vue";
import { request } from "@/service/request";

const emit = defineEmits(['addTag']);

// 3层树形菜单数据
const tabList1 = ref([]); // 第一层（根层）
const tabList2 = ref([]); // 第二层
const tabList3 = ref([]); // 第三层
const tabList4 = ref([]); // 最终按钮列表

// 当前选中的tab索引
const tab1 = ref(-1);
const tab2 = ref(-1);
const tab3 = ref(-1);
const tab4 = ref(-1);

// 添加标签事件
const onAddTag = (item) => {
  console.log("onAddTag", item);
  emit('addTag', item);
}

// https://anfine.huasun-healthcare.com/api/health_records/health_recordtag/healthRecordTagInfo/list?_t=1755997584470&name=%E6%B1%9F%E6%80%9D%E5%BF%97
// https://anfine.huasun-healthcare.com/api/health_records/health_tag/healthTagInfo/list?_t=1755997584465
const getTagList = (pid) => {
  return new Promise((resolve, reject) => {
    console.log("getTagList pid:", pid);
    const params = {};
    if (pid !== null && pid !== undefined) {
      params.pid = pid;
    }

    request.get('/health_records/health_tag_info/healthTagInfo/rootList', params, {
      useErrMsg: true
    }).then(res => {
      console.log("getTagList res====", res);
      if (res.success && res.success.records) {
        resolve(res.success.records);
      } else if (res.success) {
        // 如果直接是数组格式
        resolve(Array.isArray(res.success) ? res.success : []);
      } else {
        resolve([]);
      }
    }).catch(error => {
      console.error("getTagList error:", error);
      reject(error);
    });
  });
}

onMounted(async () => {
  try {
    console.log("获取根层数据...");
    const list = await getTagList(null); // 根层pid为null
    console.log("根层数据:", list);
    
    if (list && list.length > 0) {
      tabList1.value = list;
      tab1.value = 0; // 默认选中第一个
    } else {
      console.warn("没有获取到根层数据");
      tabList1.value = [];
    }
  } catch (error) {
    console.error("获取根层数据失败:", error);
    tabList1.value = [];
  }
})
// 级联联动：tab1变化时，获取子级数据
watch(tab1, async (newVal) => {
  console.log("tab1 变化:", newVal);
  if (newVal === -1 || !tabList1.value[newVal]) {
    return;
  }
  
  // 重置下级数据
  tabList2.value = [];
  tabList3.value = [];
  tabList4.value = [];
  tab2.value = -1;
  tab3.value = -1;
  tab4.value = -1;
  
  try {
    const pid = tabList1.value[newVal].id;
    console.log("获取第二层数据, pid:", pid);
    const list = await getTagList(pid);
    console.log("第二层数据:", list);
    
    if (list && list.length > 0) {
      tabList2.value = list;
      tab2.value = 0; // 默认选中第一个
    }
  } catch (error) {
    console.error("获取第二层数据失败:", error);
  }
});

watch(tab2, async (newVal) => {
  console.log("tab2 变化:", newVal);
  if (newVal === -1 || !tabList2.value[newVal]) {
    return;
  }
  
  // 重置下级数据
  tabList3.value = [];
  tabList4.value = [];
  tab3.value = -1;
  tab4.value = -1;
  
  try {
    const pid = tabList2.value[newVal].id;
    console.log("获取第三层数据, pid:", pid);
    const list = await getTagList(pid);
    console.log("第三层数据:", list);
    
    if (list && list.length > 0) {
      tabList3.value = list;
      tab3.value = 0; // 默认选中第一个
    }
  } catch (error) {
    console.error("获取第三层数据失败:", error);
  }
});

watch(tab3, async (newVal) => {
  console.log("tab3 变化:", newVal);
  if (newVal === -1 || !tabList3.value[newVal]) {
    return;
  }
  
  // 重置下级数据
  tabList4.value = [];
  tab4.value = -1;
  
  try {
    const pid = tabList3.value[newVal].id;
    console.log("获取第四层数据(最终按钮), pid:", pid);
    const list = await getTagList(pid);
    console.log("第四层数据(最终按钮):", list);
    
    if (list && list.length > 0) {
      tabList4.value = list;
      // 注意：这里不设置tab4.value，因为这一层是最终的按钮列表
    }
  } catch (error) {
    console.error("获取第四层数据失败:", error);
  }
});
</script>
